import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from './auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.NODE_ENV === 'production'
  //   ? 'https://api-hmzs.itheima.net/api'
  //   : process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  baseURL: 'https://api-hmzs.itheima.net/api',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.dir(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 解构数据
    const { code, msg, data } = response.data
    if (code !== 10000) {
      Message.error(msg)
      return Promise.reject(msg)
    } else {
      return data
    }
  },
  error => {
    // 提示错误信息
    Message.error(error.response.data.msg)// 提示错误信息
    return Promise.reject(error)
  }
)

export default service
